package com.gill.jwt.aop;

import com.gill.jwt.config.properties.JwtProperties;
import com.gill.jwt.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @program: my-utils-repo
 * @description:
 * @author: Gill
 * @create: 2021-03-22 16:16
 **/
@Aspect
@Component
public class AuthorizationAspect {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 校验请求是否携带token
     */
    @Around("@annotation(com.gill.jwt.annotation.Login)")
    public Object checkLogin(ProceedingJoinPoint point) throws Throwable {
        checkToken();
        return point.proceed();
    }

    /**
     * 校验token
     */
    private void checkToken(){
        HttpServletRequest request = getHttpServletRequest();
        // 获取header
        String token = request.getHeader(jwtProperties.getHeader());
        if(token == null){
            throw new SecurityException(jwtProperties.getHeader()+" can not be null");
        }
        // 校验token
        Boolean isValid = jwtUtil.isTokenValid(token);
        if(!isValid){
            throw new SecurityException(jwtProperties.getHeader()+" is illegal");
        }
        // 3. 如果校验成功，那么就将用户的信息设置到request的attribute里面
        Claims claims = jwtUtil.getClaimsFromToken(token);
        request.setAttribute("userId",claims.get("userId"));
        request.setAttribute("username",claims.get("username"));
        request.setAttribute("role",claims.get("role"));
    }

    /**
     * 获取Request
     */
    private HttpServletRequest getHttpServletRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        return attributes.getRequest();
    }
}
